<template>
	<view class="container">

		<!-- 头部 -->
		<view class="header">
			<text class="title">规划路线</text>
		</view>

		<!-- 路线规划 -->
		<view class="route-planner">
			<view class="marker-start">
				<image class="marker-image" src="/static/map_pin_start.png"></image>
				<input class="input-box" placeholder="输入起点" placeholder-class="placeholder" v-model="startLocation.name"
					@tap="chooseLocation('start')" readonly />
				<uni-icons v-if="waypoints.length === 0" type="plusempty" size="30" @click="addWaypoint"
					class="add-icon"></uni-icons>
			</view>

			<!-- 途经点列表 -->
			<view class="waypoints">
				<view class="waypoint-item" v-for="(item, index) in waypoints" :key="index">
					<view class="marker-waypoint">
						<uni-icons type="closeempty" size="30" class="delete-btn"
							@click="deleteWaypoint(index)"></uni-icons>
						<input class="input-box" v-model="waypoints[index].name" placeholder="输入途经点"
							placeholder-class="placeholder" @tap="chooseLocation('waypoint', index)" readonly />
						<!-- 只在最后一个途经点显示添加按钮 -->
						<uni-icons v-if="index === waypoints.length - 1" type="plusempty" size="30" @click="addWaypoint"
							class="add-icon"></uni-icons>
					</view>
				</view>
			</view>

			<view class="marker-end">
				<image class="marker-image" src="/static/map_pin_end.png"></image>
				<input class="input-box" placeholder="输入终点" placeholder-class="placeholder" v-model="endLocation.name"
					@tap="chooseLocation('end')" readonly />
			</view>
		</view>

		<view class="image-picker">
			<uni-file-picker v-model="imageList" :limit="maxLimit" mode="grid" fileMediatype="image"
				:image-styles="imageStyles" @select="selectFile" title="最多选择9张图片">
			</uni-file-picker>
		</view>

		<!-- 标题和描述 -->
		<view class="content-section">
			<!-- 标题输入框 -->
			<view class="input-item">
				<input class="title-input" type="text" placeholder="选择一个炫酷的标题吧" v-model="title" />
				<view class="divider-line"></view>
			</view>

			<!-- 描述输入框 -->
			<view class="input-item">
				<textarea class="description-input" placeholder="随心记录你的感受" rows="4" v-model="description"></textarea>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-buttons">
			<button class="btn draft">草稿</button>
			<button class="btn publish" @click="publish">发布</button>
		</view>

	</view>
</template>

<script>
	import {
		postRouting
	} from '@/api/posts.js';
	export default {
		data() {
			return {
				uploadedImageUrls: [],
				nodes: [],
				startLocation: {
					name: '',
					latitude: null,
					longitude: null
				},
				endLocation: {
					name: '',
					latitude: null,
					longitude: null
				},
				waypoints: [{
					name: '',
					latitude: null,
					longitude: null
				}],

				title: '',
				description: '',
				imageList: [], // 图片列表
				maxLimit: 9, // 动态限制的最大值
				isPublishing: false,
				imageStyles: {
					width: '230rpx',
					height: '230rpx',
					border: {
						radius: '2px'
					}
				},
			}
		},
		onShow() {
			var checkLoginFunction = require('../../common/chechLoginFunction.js')
			if (checkLoginFunction.checkLogin() == null) {
				return
			}
		},
		methods: {
			selectFile(newFiles) {
				// 确保 this.imageList 和 newFiles.tempFiles 都是数组
				if (!Array.isArray(this.imageList)) {
					this.imageList = []; // 初始化为数组
				}

				// 检查 newFiles.tempFiles 是否存在且为数组
				const filesToAdd = Array.isArray(newFiles.tempFiles) ? newFiles.tempFiles : [];

				// 将新选择的文件追加到现有的文件列表中
				this.imageList = [...this.imageList, ...filesToAdd];

				// 如果文件数量超出9张，修正为最多9张
				if (this.imageList.length > 9) {
					this.imageList = this.imageList.slice(0, 9);
				}

				// 动态更新 limit，确保只能选择最多9张图片
				this.maxLimit = 9 - this.imageList.length;
			},

			updateNodes() {
				this.nodes = []; // 清空 nodes 数组

				// 添加开始节点
				if (this.startLocation.name) {
					this.nodes.push({
						latitude: this.startLocation.latitude,
						longitude: this.startLocation.longitude,
						name: this.startLocation.name
					});
				}

				// 添加途径节点
				this.waypoints.forEach(waypoint => {
					if (waypoint.name) {
						this.nodes.push({
							latitude: waypoint.latitude,
							longitude: waypoint.longitude,
							name: waypoint.name
						});
					}
				});

				// 添加结束节点
				if (this.endLocation.name) {
					this.nodes.push({
						latitude: this.endLocation.latitude,
						longitude: this.endLocation.longitude,
						name: this.endLocation.name
					});
				}
			},

			//点击发布按钮调用
			async publish() {
				if (this.isPublishing) {
					uni.showToast({
						title: '正在发布中，请稍候...',
						icon: 'none'
					});
					return; // 防止重复点击
				}
				// 校验输入内容
				if (!this.startLocation.name || !this.endLocation.name) {
					uni.showToast({
						title: '请填开始节点和结束节点',
						icon: 'none',
					});
					return; // 终止函数执行
				}
				// 检查每个途径节点的内容
				const emptyWaypoint = this.waypoints.some(waypoint => !waypoint.name);
				if (emptyWaypoint) {
					uni.showToast({
						title: '请检查所有途径节点是否已填写',
						icon: 'none',
					});
					return; // 终止函数执行
				}
				// 更新 nodes 数组
				this.updateNodes();
				console.info(this.imageList);
				// 获取表单数据
				// 创建一个 FormData 对象

				// 发送请求
				this.isPublishing = true; // 设置发布状态
				this.uploadFilesAndPost();

			},
			async uploadFilesAndPost() {
				this.uploadedImageUrls = []; // 重置数组

				const uploadUrl = 'https://www.aaxing14.top:8101/user/file/upload'; // 示例接口地址
				const formData = {
					'biz': 'route_img'
				};

				// 创建一个包含所有文件上传的 Promise 数组
				const uploadPromises = this.imageList.map((file) => {
					return new Promise((resolve, reject) => {
						uni.uploadFile({
							url: uploadUrl,
							filePath: file.url, // 指定文件路径
							name: 'file', // 指定文件字段名
							formData: formData,
							header: {
								'token': uni.getStorageSync('token'),
							},
							success: (res) => {
								const data = JSON.parse(res.data);
								if (data && data.code == 0) { // 假设接口返回的图片 URL 字段名为 url
									this.uploadedImageUrls.push(data.data); // 将 URL 存入数组
								}
								resolve();
							},
							fail: (err) => {
								console.error('文件上传失败:', err);
								reject(err);
							}
						});
					});
				});

				// 等待所有文件上传完成
				try {
					await Promise.all(uploadPromises);

					// 所有文件上传成功后执行后续逻辑
					const data = {
						imageList: JSON.stringify(this.uploadedImageUrls),
						route: JSON.stringify(this.nodes),
						title: this.title,
						description: this.description,
						address: JSON.stringify(uni.getStorageSync('address')) // 读取存储的地址
					};

					const response = await postRouting(data);

					if (response.code == 0) {
						uni.showToast({
							title: '发布成功',
							icon: 'success',
						});
						this.uploadedImageUrls = [];
						this.nodes = [];
						this.startLocation = {
							name: '',
							latitude: null,
							longitude: null
						};
						this.endLocation = {
							name: '',
							latitude: null,
							longitude: null
						};
						this.waypoints = [{
							name: '',
							latitude: null,
							longitude: null
						}];
						this.title = '';
						this.description = '';
						this.imageList = [];
					}

				} catch (error) {
					console.error('发布失败:', error);
					uni.showToast({
						title: '发布失败，请重试',
						icon: 'none',
					});
				} finally {
					this.isPublishing = false; // 无论成功或失败都重置发布状态
				}
			},

			addWaypoint() {
				if (this.waypoints.length < 5) { // 限制最多5个途经点
					this.waypoints.push({
						value: ''
					})
				}
			},
			deleteWaypoint(index) {
				this.waypoints.splice(index, 1)
			},
			chooseLocation(type, index) {
				uni.chooseLocation({
					success: (res) => {
						console.info(res)
						if (type === 'start') {
							this.startLocation.name = res.name;
							this.startLocation.latitude = res.latitude; // 保存纬度
							this.startLocation.longitude = res.longitude; // 保存经度
							// 校验开始节点与第一个途径节点、结束节点
							if (this.waypoints.length > 0 && this.waypoints[0].name === res.name) {
								uni.showToast({
									title: '开始节点与第一个途经点相同',
									icon: 'none'
								});
							} else if (this.waypoints.length <= 0 && this.endLocation.name === res
								.name) {
								uni.showToast({
									title: '开始节点与结束节点相同',
									icon: 'none'
								});
							}
						} else if (type === 'end') {
							this.endLocation.name = res.name;
							this.endLocation.latitude = res.latitude; // 保存纬度
							this.endLocation.longitude = res.longitude; // 保存经度
							// 校验结束节点与最后一个途径节点、开始节点
							if (this.waypoints.length > 0 && this.waypoints[this.waypoints.length -
									1].name === res.name) {
								uni.showToast({
									title: '结束节点与最后一个途经点相同',
									icon: 'none'
								});
							} else if (this.waypoints.length <= 0 && this.startLocation.name ===
								res.name) {
								uni.showToast({
									title: '结束节点与开始节点相同',
									icon: 'none'
								});
							}
						} else if (type === 'waypoint' && index !== undefined) {
							//因为会先addWaypoint增加一个空节点，通过index-1获取到上一个节点再与该节点做判断
							const previousWaypoint = index > 0 ? this.waypoints[index - 1] :
								null; //上一节点
							const nextWaypoint = index < this.waypoints.length - 1 ? this
								.waypoints[index + 1] : null; //下一节点
							//校验上一个节点
							if (index > 0 && previousWaypoint.name === res.name) {
								uni.showToast({
									title: '此途径点与上一个途经点相同',
									icon: 'none'
								});
							}
							// 校验下一个节点
							if (index < this.waypoints.length - 1 && nextWaypoint.name === res
								.name) {
								uni.showToast({
									title: '此途径点与下一个途经点相同',
									icon: 'none'
								});
							}
							//校验开始节点
							if (index == 0 && this.startLocation.name === res.name) {
								uni.showToast({
									title: '此途径点与开始节点相同',
									icon: 'none'
								});
							}
							//校验结束节点
							if (index == this.waypoints.length - 1 && this.endLocation.name === res
								.name) {
								uni.showToast({
									title: '此途径点与结束节点相同',
									icon: 'none'
								});
							}
							// 更新途径节点
							this.$set(this.waypoints, index, {
								name: res.name,
								latitude: res.latitude, // 保存纬度
								longitude: res.longitude // 保存经度
							});

						}
					},
					fail: (err) => {
						console.log('选择地点失败', err);
					}
				});
			}
		}
	};
</script>

<style>
	.container {
		width: 750rpx;
		min-height: 100vh;
		background: white;
		position: relative;
	}


	.header {
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		/* 水平居中 */
		padding-top: 80rpx;
		padding-bottom: 30rpx;

	}

	.title {
		font-size: 34rpx;
		color: #181818;
	}

	.route-planner {
		padding: 0 32rpx;
	}

	.route-points {
		display: flex;
		gap: 20rpx;
	}

	.marker-image {
		width: 34rpx;
		height: 44rpx;
		margin-right: 68rpx;
		margin-bottom: 15rpx;
		margin-left: 62rpx;
	}

	.marker-start,
	.marker-end,
	.marker-waypoint {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.route-input {
		flex: 1;
	}

	.input-box {
		width: 367rpx;
		height: 64rpx;
		background: white;
		border-radius: 24rpx;
		border: 2rpx solid #E5E5E5;
		margin-right: 20rpx;
		margin-bottom: 12rpx;
		padding: 0 26.24rpx;
		font-size: 24rpx;
	}

	.placeholder {
		color: #ACACAC;
		font-weight: 300;
	}

	.image-picker {
		margin-top: 72rpx;
		padding: 0 32rpx;
	}

	.content-section {
		margin-top: 72rpx;
		padding: 0 32rpx;
	}

	.waypoints {
		margin-left: 54rpx;
		/* 对齐输入框 */
	}

	.waypoint-item {
		display: flex;
		align-items: center;
		margin-bottom: 12rpx;
	}

	.delete-btn {
		font-size: 32rpx;
		color: #999;
		margin-right: 76rpx;
		width: 34rpx;
		height: 34rpx;
		text-align: center;
		display: flex;
		align-items: center;
	}

	.add-btn {
		position: absolute;
		right: -60rpx;
		font-size: 32rpx;
		color: #2F6EF5;
		width: 44rpx;
		height: 44rpx;
		line-height: 40rpx;
		text-align: center;
	}

	.input-item {
		margin-bottom: 24rpx;
		color: #7B7B7B;
		font-size: 28rpx;
	}

	.divider-line {
		height: 2rpx;
		background: #DDDDDD;
		margin-top: 16rpx;
	}

	.bottom-buttons {
		position: fixed;
		bottom: 112rpx;
		right: 32rpx;
		display: flex;
		gap: 16rpx;
	}

	.btn {
		width: 120rpx;
		height: 56rpx;
		border-radius: 28rpx;
		font-size: 28rpx;
		font-weight: 300;
		line-height: 56rpx;
	}

	.btn.draft {
		background: #DDDDDD;
		color: #7B7B7B;
	}

	.btn.publish {
		background: #2F6EF5;
		color: white;
	}
</style>